<?php
class relation
{
   public function __construct($args)
   {
       foreach($args as $ref => $type_column)
       {
           $this->_ref = $ref;
           $this->_type = $type_column['type'];
           $this->_column = $type_column['column'];
       }
   
   }
   protected $_ref;
   protected $_type;
   protected $_column;
   protected $_ids; // for hasmany
   protected $_id; // for hasone & belongto

   public function __get($property)
   {
       return $this->$property;
   }
   public function loadrelatedentities()
   {
       $type = $this->_type; 
       if($this instanceof hasmany)
       {
           return matrix::get($type.'dao')->find($this->_ids);    
       }

       if($this instanceof hasone || $this instanceof belongto)
       {
           return matrix::get($type.'dao')->find($this->_id);    
       }
   }

   public function addpendref($entity)
   {
       $column = $this->_column;
       $binds[':xxid'] = $entity->id;
       $type = $this->_type;
       $sql = "select id from $type where $column = :xxid";

       $id = matrix::get('dbexecuter')->queryValue($sql,'id', $binds);
       if(empty($id))  return;
       $this->_id = $id;
       //这里只是 load下 真正的加载要在 __get方法里做
      // $ref = $this->_ref;
      // $entity->$ref = $this;
   }

}
class hasone extends relation
{
    
}

class hasmany extends relation
{

   public function addpendref($entity)
   {
       $column = $this->_column;
       $binds[':xxid'] = $entity->id;
       $type = $this->_type;
       $sql = "select id from $type where $column = :xxid";
       $ids = matrix::get('dbexecuter')->queryColumn($sql,'id', $binds);
       if(empty($ids))  return ;
       $this->_ids = $ids;
       //$ref = $this->_ref;
       //$entity->$ref = $this;
   }

}

class belongto extends relation
{

    // score belongto user type - user column - userid  ref - user 
   public function addpendref($entity)
   {
       $column = $this->_column;
       $this->_id = $entity->$column;
   }


}


